﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Mystery.SharePoint
{
	/// <summary>
	/// Extension methods for SPUserCollection
	/// </summary>
	public static class SPUserCollectionExtensions
	{
		/// <summary>
		/// Finds the user with the specified login
		/// </summary>
		/// <param name="users"></param>
		/// <param name="login">The login to find</param>
		/// <returns>Reference to the user, or null if not found</returns>
		public static SPUser FindByLogin(this SPUserCollection users, string login)
		{
			if (users == null) throw new ArgumentNullException("users");
			if (string.IsNullOrEmpty(login) == true) throw new ArgumentNullException("login");

			try
			{
				return users[login];
			}
			catch (Exception)
			{
				return null;
			}
		}
		/// <summary>
		/// Adds a user if it doesn't already exist
		/// </summary>
		/// <param name="users"></param>
		/// <param name="loginName"></param>
		/// <returns></returns>
		public static SPUser Add(this SPUserCollection users, string login)
		{
			if (users == null) throw new ArgumentNullException("users");
			if (string.IsNullOrEmpty(login) == true) throw new ArgumentNullException("login");

			try
			{
				return users[login];
			}
			catch (Exception)
			{
				users.Add(login, null, null, null);
				Logger.L.AddInformation(Category.Administration, "Adding user {0}", login);
				return users[login];
			}
		}

		/// <summary>
		/// Synchronizes the users against a target
		/// </summary>
		/// <param name="users">Source </param>
		/// <param name="target">The target collection</param>
		/// <param name="siteAdmin">True to sync site admins, false to sync normal users</param>
		public static void Synchronize(this SPUserCollection users, SPUserCollection target, bool siteAdmin)
		{
			// make sure all users exist in the target
			foreach (SPUser user in users)
			{
				if (user.IsSiteAdmin == siteAdmin)
				{
					SPUser u = target.Add(user.LoginName);
					u.IsSiteAdmin = siteAdmin;
					u.Update();
				}
			}
			// find users in the target that are no longer at the source
			List<SPUser> remove = new List<SPUser>();

			foreach (SPUser user in target)
			{
				if (user.IsSiteAdmin == siteAdmin)
				{
					if (users.FindByLogin(user.LoginName) == null)
					{
						remove.Add(user);
					}
				}
			}
			foreach (SPUser user in remove)
			{
				users.Remove(user.LoginName);
			}
		}
	}
}
